<template>
  <div class="home">
    <el-row class="mb-4">
      <el-button :onclick="addAddress">新增收货地址</el-button>
      <el-button :onclick="exportAddress">导出收货地址</el-button>
    </el-row>
    <el-table :data="state.tableData.data">
      <el-table-column v-for="item in state.colunm" :prop="item.key" :key="item.key" :label="item.lable">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" @click="editAddress(scope.row)" size="small">修改</el-button>
          <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确认删除?"
              @confirm="deleteAddress(scope.row)"
          >
            <template #reference>
              <el-button link type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class='block flex justify-end' v-if='state.tableData.total > 0'>
      <el-pagination v-model:currentPage="state.searchInput.PageIndex" v-model:page-size="state.searchInput.PageSize"
                     :page-sizes="[10, 50, 200, 1000]" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="getData"
                     @current-change="getData" :total="state.tableData.total"/>
    </div>
  </div>

  <el-dialog :close-on-click-modal="false" v-model="state.dialogVisible" :title="state.title" width="40%">
    <el-form :model='addData'
             :rules="rules"
             ref="ruleFormRef"
             label-width='130px'
             status-icon
             class='dialogForm'>
      <el-form-item label="收货人" prop="consignee">
        <el-input v-model="addData.consignee"/>
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input v-model="addData.phoneNumber"/>
      </el-form-item>
      <el-form-item label="收货地址" prop="regionCode">
        <el-cascader
            style="width: 100%;"
            placeholder="收货地址"
            :options="state.options"
            @change='addressChange'
            v-model="addData.regionCode">
        </el-cascader>
      </el-form-item>
      <el-form-item label="详细地址" prop="detailedAddress">
        <el-input v-model="addData.detailedAddress"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
        <el-button @click="()=>state.dialogVisible=false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts">
import {defineComponent, onMounted, reactive, ref} from "vue";
import {regionData, CodeToText} from 'element-china-area-data'
import type {FormInstance, FormRules} from 'element-plus'
import axios from "axios";
import {ElMessage} from "element-plus";
import {ReceivingAddressManagement} from '../api/address/types';
import * as XLSX from 'xlsx'

export default defineComponent({
  components: {},
  setup() {
    onMounted(async () => {
      getData();
    });
    const state = reactive({
      tableData: {data: [], total: 0},
      dialogVisible: false,
      title: '',
      searchInput: {PageIndex: 1, PageSize: 10},
      colunm: [
        {lable: '收货人', key: 'consignee'},
        {lable: '手机号码', key: 'phoneNumber'},
        {lable: '收货地址', key: 'region'},
        {lable: '详细地址', key: 'detailedAddress'}],
      options: regionData,
    });
    let addData = ref(reactive({
      consignee: '',
      phoneNumber: '',
      region: '',
      regionCode: [],
      detailedAddress: ''
    }));
    const ruleFormRef = ref<FormInstance>()
    const getData = () => {
      axios.get('/ReceivingAddressManagement', {params: state.searchInput}).then(function (response) {
        state.tableData = response.data;
      })
    }
    const addressChange = (arr) => {
      addData.value.region = CodeToText[arr[0]] + CodeToText[arr[1]] + CodeToText[arr[2]];
    }
    const validatePass = (rule: any, value: any, callback: any) => {
      if (value && value != "") {
        if (!/^1[0-9]{10}$/.test(value)) {
          callback(new Error("请输入正确的手机号码"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入手机号码"));
      }
    }
    const rules = reactive<FormRules>({
      consignee: [{required: true, message: '请输入收货人', trigger: 'change'}],
      phoneNumber: [{required: true, validator: validatePass, trigger: 'change'}],
      regionCode: [{required: true, message: '请选择收货地址', trigger: 'change'}],
      detailedAddress: [{required: true, message: '请输入详细地址', trigger: 'change'}],
    })

    const submitForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.validate((valid, fields) => {
        if (valid) {
          axios.post('/ReceivingAddressManagement', addData.value)
              .then(function (response) {
                if (response.status == 200) {
                  ElMessage.success(response.data);
                  state.dialogVisible = false;
                  getData();
                } else {
                  ElMessage.error(response.data)
                }
              })
        } else {
          return false
        }
      })
    }

    const addAddress = () => {
      Object.keys(addData.value).forEach(key => (addData.value[key] = ''));
      state.title = '新增收货地址';
      state.dialogVisible = true;
    }
    const editAddress = (row) => {
      axios.get('/ReceivingAddressManagement/' + row.id,).then(function (response) {
        addData.value = response.data;
      })
      state.title = '修改收货地址';
      state.dialogVisible = true;
    }

    const deleteAddress = (row) => {
      axios.delete('/ReceivingAddressManagement/' + row.id,).then(function (response) {
        ElMessage.success("删除成功");
        getData();
      })
    }
    let head = {
      consignee: '收货人',
      phoneNumber: '手机号码',
      region: '收货地址',
      detailedAddress: '详细地址',
    }
    const  exportAddress=()=>{

      const tempData: any = [];
      state.tableData.data.map((item,index) => {
        const obj = {}
        for (const k in item) {
          if (head[k]) {
            obj[head[k]] = item[k]
          }
        }
        tempData.push(obj);
      });
      //创建工作表
      const data = XLSX.utils.json_to_sheet(tempData)
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      // 将工作表放入工作簿中
      XLSX.utils.book_append_sheet(wb, data, 'data')
      // 生成文件并下载
      XLSX.writeFile(wb, '地址.xlsx')
    }
    return {
      state,
      onMounted,
      getData,
      addressChange,
      addAddress,
      validatePass,
      submitForm,
      ruleFormRef,
      rules,
      addData,
      editAddress,
      deleteAddress,
      exportAddress
    }
  }
})
</script>

<style scoped>

</style>